/**
 * 主框架左侧导航菜单面板
 */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Layout, Menu } from 'antd';
import AntdIcon from '../../components/AntdIcon';

import { selectMenu } from '../../redux/actions/menus'

// 创建Menu控件所需item数据
function getItem(label, key, icon, children, type) {
    return {
        key,
        icon,
        children,
        label,
        type,
    };
}

class TraSider extends Component {

    componentDidMount() {
        let { menus, location, selectMenu } = this.props;
        let menu = menus.find(m => m.path === location.pathname)
        if (menu && !menu.selected) {
            selectMenu(menu.menuId)
        }
    }

    onSelect = ({key}) => {
        let { menus, onSelect, selectMenu } = this.props;
        let menu = menus.find(m => m.menuId === key*1)
        selectMenu(key*1)
        onSelect(menu)
    }

    render() {
        // 从redux中获取：api请求回来的菜单数据列表menus
        let { menus } = this.props;
        if (menus.length === 0) {
            return <Layout.Sider collapsible />
        }
        let selectedMenu = menus.find(m => '/main/' + m.path === this.props.location.pathname || m.selected) || menus[0]
        console.log('selectedMenu', selectedMenu, menus)
        let expandedKeys = menus.filter(m => m.expanded).map(m => m.menuId + '')
        // 根据menuItems创建Menu控件需要的items数据
        let items = menus.map(item => getItem(item.menuName, '' + item.menuId, <AntdIcon icon={item.icon} />))
        // 设置item的children
        items.forEach(item => {
            menus.forEach(mi => {
                if (mi.parentId === item.key*1) {
                    let i = items.find(i => i.key*1 === mi.menuId)
                    if (!item.children) {
                        item.children = [i]
                    } else {
                        item.children.push(i)
                    }
                }
            })
        });
        // 获取顶级菜单
        let topMenus = menus.filter(m => m.parentId === 0)
        items = items.filter(item => topMenus.find(m => m.menuId === item.key*1))
        return (
            <Layout.Sider collapsible>
                <Menu
                    theme='dark'
                    mode="inline"
                    items={items}
                    onSelect={this.onSelect}
                    defaultOpenKeys={expandedKeys}
                    defaultSelectedKeys={[selectedMenu.menuId + '']}
                />
            </Layout.Sider>
        )
    }
}

const mapStateToProps = (state) => ({
    menus: state.menus
})

const mapDispatchToProps = {
    selectMenu
}

export default connect(mapStateToProps, mapDispatchToProps)(TraSider)
